/**
 * Service Worker注册工具
 * Story 4: Task 5 - Service Worker缓存实现
 */

/**
 * 注册Service Worker
 */
export async function registerServiceWorker(): Promise<ServiceWorkerRegistration | null> {
  // 仅在生产环境且支持Service Worker的浏览器中注册
  if (import.meta.env.PROD && 'serviceWorker' in navigator) {
    try {
      const registration = await navigator.serviceWorker.register('/sw.js', {
        scope: '/',
      })

      console.log('[SW] Service Worker registered successfully:', registration.scope)

      // 检查更新
      registration.addEventListener('updatefound', () => {
        const newWorker = registration.installing

        if (newWorker) {
          newWorker.addEventListener('statechange', () => {
            if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
              // 新版本可用，提示用户刷新
              console.log('[SW] New version available, please refresh')

              // 可以显示一个提示框让用户刷新
              if (window.confirm('发现新版本，是否立即更新？')) {
                newWorker.postMessage('SKIP_WAITING')
                window.location.reload()
              }
            }
          })
        }
      })

      // 监听控制器变化
      navigator.serviceWorker.addEventListener('controllerchange', () => {
        console.log('[SW] Controller changed, reloading page')
        window.location.reload()
      })

      return registration
    } catch (error) {
      console.error('[SW] Service Worker registration failed:', error)
      return null
    }
  }

  return null
}

/**
 * 注销Service Worker
 */
export async function unregisterServiceWorker(): Promise<boolean> {
  if ('serviceWorker' in navigator) {
    const registration = await navigator.serviceWorker.ready

    if (registration) {
      const unregistered = await registration.unregister()
      console.log('[SW] Service Worker unregistered:', unregistered)
      return unregistered
    }
  }

  return false
}

/**
 * 清除所有缓存
 */
export async function clearAllCaches(): Promise<void> {
  if ('caches' in window) {
    const cacheNames = await caches.keys()

    await Promise.all(
      cacheNames.map((name) => {
        console.log('[SW] Deleting cache:', name)
        return caches.delete(name)
      })
    )

    console.log('[SW] All caches cleared')
  }
}

/**
 * 获取Service Worker状态
 */
export function getServiceWorkerStatus(): {
  supported: boolean
  registered: boolean
  controller: ServiceWorker | null
} {
  const supported = 'serviceWorker' in navigator

  return {
    supported,
    registered: supported && navigator.serviceWorker.controller !== null,
    controller: supported ? navigator.serviceWorker.controller : null,
  }
}

/**
 * 检查Service Worker更新
 */
export async function checkForUpdates(): Promise<boolean> {
  if ('serviceWorker' in navigator) {
    const registration = await navigator.serviceWorker.ready

    if (registration) {
      await registration.update()
      console.log('[SW] Checked for updates')
      return true
    }
  }

  return false
}
